package com.kingtsoft.study.webserivce.imp;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.kingtsoft.study.constant.Describable;
import com.kingtsoft.study.constant.DescribableEnum;
import com.kingtsoft.study.exception.BusinessException;
import com.kingtsoft.study.model.StudyHomeworkDetail;
import com.kingtsoft.study.util.FileUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.kingtsoft.study.common.ContextHolder;
import com.kingtsoft.study.constant.ParamConstants;
import com.kingtsoft.study.model.StudyHomework;
import com.kingtsoft.study.service.StudyHomeworkService;
import com.kingtsoft.study.webserivce.WebStudyHomeworkService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@Service
public class WebStudyHomeworkServiceImpl implements WebStudyHomeworkService {


	@Reference
	private StudyHomeworkService studyHomeworkService;


	/**
	 * 获取作业
	 *
	 * @param id 作业主键
	 * @return 作业
	 * @author jerry.pan
	 * @date 2017-03-30 15:08:11
	 */
	@Override
	public StudyHomework load(String id){
		return studyHomeworkService.load(id);
	}

    /**
     * 分页获取老师布置的作业的列表
     *
     * @return pageInfo
     * @author jerry.pan
     * @date 2017-03-30 15:08:11
     */
	@Override
	public PageInfo<StudyHomework> listPage(PageInfo page, StudyHomework studyHomework) {
		return studyHomeworkService.listPage(page, studyHomework);
	}

	/**
	 * 获取老师布置的作业的列表
	 *
	 * @return list
	 * @author jerry.pan
	 * @date 2017-03-30 15:08:11
	 */
	@Override
	public List<StudyHomework> listAll(StudyHomework studyHomework) {
		return studyHomeworkService.listAll(studyHomework);
	}

	/**
    *
    * @Title: addHomework
    * @Description: 老师发布作业，保存homework
    * @author: shenlx
    * @param studyHomework
    * @return: void
    */
	@Override
	public void addHomework(StudyHomework studyHomework) {
		studyHomework.setUserId(ContextHolder.getSessionUser().getId());
		studyHomework.setTeacherId(ContextHolder.getSessionTeacher().getId());
		studyHomework.setPublishDate(new Date());
		studyHomework.setPublishStatus(ParamConstants.PUBLISHSTATUS_1);
		studyHomeworkService.addHomework(studyHomework);
	}


	/**
	 * 保存上传文件
	 *
	 * @param file
	 * @author jerry.pan
	 * @date 2017-04-01 15:38:22
	 */
	public StudyHomework saveUpload(MultipartFile file, StudyHomework studyHomework) {
		String filename = file.getOriginalFilename();
		String suffix = FileUtil.getFileSuffix(filename);
		String relativePath;
		//保存到文件夹
		try {
			relativePath = FileUtil.upload(file);
			//改为通过id下载的方式
//            String url = FileUtil.getFileUrl(relativePath);//获取下载路径
//            studyHomeworkDetail.setUrl(url);
		} catch (IOException e) {
			throw new BusinessException(DescribableEnum.FILE_UPLOAD_ERROR);
		}
		studyHomework.setFilename(filename);
		studyHomework.setFileSize(BigDecimal.valueOf(file.getSize()));
		studyHomework.setSuffix(suffix);
		studyHomework.setPath(relativePath);
		if(StringUtils.isNotBlank(studyHomework.getId())){//不为空,已经在数据库储存过
			studyHomework = studyHomeworkService.saveUpload(studyHomework);
		}
		return studyHomework;
	}

	/**
	 * 下载文件
	 * @param response
	 * @param id 学生作业表主键
	 * @author jerry.pan
	 */
	public void downloadFile(HttpServletResponse response, String id){
		StudyHomework homework = this.load(id);
		if (homework == null) {
			throw new BusinessException(DescribableEnum.FILE_NOT_EXIST);
		}
		String filename = homework.getFilename();
		String filePath = FileUtil.getPath(homework.getPath());
		File file = new File(filePath);
		if (!file.exists()) {
			throw new BusinessException(DescribableEnum.FILE_NOT_EXIST);
		}
		try {
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
			OutputStream out = response.getOutputStream();
			FileUtils.copyFile(file, out);
		} catch (IOException e) {
			throw new BusinessException(DescribableEnum.FILE_DOWNLOAD_ERROR);
		}
	}

	/**
	 * 删除上传文件
	 *
	 * @param
	 * @author jerry.pan
	 * @date 2017-04-01 15:38:22
	 */
	public void deleteFile(String id) {
		Map resultMap = studyHomeworkService.deleteFile(id);
		Describable describable = (Describable) MapUtils.getObject(resultMap, "describable");
		if(!DescribableEnum.SUCCESS.equals(describable)){
			throw new BusinessException(describable);
		}
	}
}
